﻿using System.Text;

namespace AuSys.Utils.StringUtils
{
    public static class UrlSafeBase64
    {
        public const char base64Plus = '+';
        public const char base64Slash = '/';
        public const char urlSafeBase64Plus = '-';
        public const char urlSafeBase64Slash = '_';
        public const char base64Equal = '=';
        public static string Encode(byte[] data)
        {
            string base64String = Convert.ToBase64String(data);
            string urlSafeBase64String = base64String
                .Replace(base64Plus, urlSafeBase64Plus)
                .Replace(base64Slash, urlSafeBase64Slash)
                .TrimEnd(base64Equal);
            return urlSafeBase64String;
        }
        public static byte[] Decode(string urlSafeBase64String)
        {
            string base64String = urlSafeBase64String
                .Replace(urlSafeBase64Plus, base64Plus)
                .Replace(urlSafeBase64Slash, base64Slash);
            int paddingLength = (4 - base64String.Length % 4) % 4;
            base64String = base64String.PadRight(base64String.Length + paddingLength, base64Equal);
            return Convert.FromBase64String(base64String);
        }
        public static string EncodeFromUtf8String(string data)
            => Encode(Encoding.UTF8.GetBytes(data));
        public static string DecodeToUtf8String(string urlSafeBase64String)
            => Encoding.UTF8.GetString(Decode(urlSafeBase64String));
    }
}
